define(function(require,exports,module){
  
  //图片放大镜插件
  // require.async(['/plugins/etalage/jquery.etalage.min','/plugins/etalage/etalage.css'],function(){
  //   require.async('scoreMall/etalage');//调用JS
  // });
 

  //兑换操作
  var $addressId,
      $validScore,
      $calculate,
      $scoreAmount = $('.scoreAmount'),  //所需积分
      $remainAmount = $('.remainAmount').text(),//剩余商品数量既最高数量
      $reduce = $('.reduce'),                   //减少件数
      $add = $('.add'),                         //增加件数
      $amountInput = $('.amountInput'),   //兑换件数
      $yesChange = $('.yesChange'),             //确定兑换
      $cancelChange = $('.cancelChange');       //取消兑换


  //兑换数量增加 
  $add.click(function(){
    if(!$add.hasClass("disabled"))
    {
      $amountInput.val(parseInt($amountInput.val()) + 1);
      if(parseInt($amountInput.val()) >= parseInt($remainAmount))
      {
        $amountInput.val(parseInt($remainAmount));
        $add.addClass("disabled");
      }
      else
      {
        $reduce.removeClass("disabled");
      }
    }    
  });
  if(parseInt($remainAmount) == 0)
  {
    $add.addClass("disabled");
  }

  //兑换数量减少
   $reduce.click(function(){
    if(!$reduce.hasClass("disabled"))
    {
      $amountInput.val(parseInt($amountInput.val()) - 1);
      if($amountInput.val() <= '1')
      {
        $reduce.addClass("disabled");
        $amountInput.val('1');
      }
      else
      {
        $add.removeClass("disabled");
      }
    }    
  });
   
   $amountInput.on("keyup",function(){
	   	if($amountInput.val().match(/^0+\d+/)){
	           this.value = $amountInput.val().replace(/^0+(\d+)/, '$1');
	       }		
   });
   $amountInput.on("blur focus ",function(){
	   if($amountInput.val() == 0 || $amountInput.val() == ''){
	   		$amountInput.val("1");
	   	}
   });
   
   
   
   //判断数量输入框数字是否符合规则
   $('.amountInput').blur(function(){
       $(this).val(parseInt($(this).val()));
   })
  /* $('.amountInput').keyup(function(){
      this.value=this.value.replace(/\D/g,'')
      if($amountInput.val() >= parseInt($remainAmount))
      {
        $add.addClass("disabled");
        $reduce.removeClass("disabled");
        $amountInput.val(parseInt($remainAmount))
      }
      else if($amountInput.val() < parseInt($remainAmount))
      {
        $add.removeClass("disabled");
        if($amountInput.val() <= 1)
        {
          $reduce.addClass("disabled");
        }
        else
        {
          $reduce.removeClass("disabled");
        }
      }
   })*/


   //判断积分是否足够
  $validScore = $('.yesChange').attr('data-score');
  $calculate = parseInt($scoreAmount.html())*parseInt($amountInput.val());
  if($validScore >= $calculate)//积分数是否大于所需积分数
  {
    //是否设置地址 
    $('.yesChange').click(function(){
        require.async(['/plugins/layer-v1.8.4/skin/layer.css','/plugins/layer-v1.8.4/layer.min'],function(){
          
          if(parseInt($remainAmount) > 0)//判断库存
          {
            if($("#receivingInfo").val() == 'true'){//弹出订单详情以及地址
            	
                $.layer({
                    type: 1,
                    closeBtn: [0,true],
                    title: "&nbsp;&nbsp;",
                    area: ['874px', '220px'],
                    offset:['180px', ''],
                    border: [1, 1, '#cecfd0'],
                    page: {
                        html: '<div class="tipsWrap w794"><table class="table table-bordered"><thead><tr><th>商品名称</th><th>数量</th><th>消耗积分</th><th>备注</th></tr></thead><tbody><tr><td class="goodsName"></td><td class="goodsAmount"></td><td class="runScore"></td><td class="preNote"></td></tr></tbody></table><div id="orderDetail"></div></div>'
                    },
                    success:function(){
                      $.ajax({
                        url:"/member/score/getReceivingInfos.html?randomTime=" + (new Date()).getTime(),
                        type:"get",
                        cache:false,
                        dataType:"json",
                        success:function(json){
                                $("#orderDetail").html(Handlebars.compile(require("../../tpl/scoreMall/orderDetail.tpl"))(json));
                                var goodsName = $('.goodsTitle').text(),
                                    yesChangeId = $('.yesChange').attr('data-id'),
                                    addressId = $('.orderList li').attr('data-addressId');
                                $('.goodsName').text(goodsName);
                                $('.goodsAmount').text($amountInput.val());
                                $('.runScore').text(parseInt($scoreAmount.html())*parseInt($amountInput.val()));
                                //判断是否为虚拟商品
                                if($('#virtual').val() == 'true')
                                {
                                  //$('.orderList').remove();
                                  $('.preNote').text('商品将于当天进行发货');
                                  $('.orderList li').each(function(){
                                  	
                                      if($(this).attr('data-val') == 'true')
                                      {	
                                        $(this).append('<label class="defaultClass"><span>默认地址</span></label>');
                                        $(this).addClass('check');
                                        $(this).find('.defaultAddress').prop('checked',true);
                                      }
                                      else if($(this).attr('data-val') == 'false')
                                      {
                                        $(this).removeClass('check');
                                        $(this).find('.defaultAddress').prop('checked',false);
                                      }
                                      else if($(this).attr('data-val') == '')
                                      {
                                        $(this).removeClass('check');
                                        $(this).find('.defaultAddress').prop('checked',false);
                                      }
                                    })
                                }
                                else if($('#virtual').val() == 'false')
                                {
                                  $('.preNote').text('3-7个工作日内进行审核发货');
                                  //默认地址li状态
                                  $('.orderList li').each(function(){
                                	
                                  if($(this).attr('data-val') == 'true')
                                  {	
                                    $(this).append('<label class="defaultClass"><span>默认地址</span></label>');
                                    $(this).addClass('check');
                                    $(this).find('.defaultAddress').prop('checked',true);
                                  }
                                  else if($(this).attr('data-val') == 'false')
                                  {
                                    $(this).removeClass('check');
                                    $(this).find('.defaultAddress').prop('checked',false);
                                  }
                                  else if($(this).attr('data-val') == '')
                                  {
                                    $(this).removeClass('check');
                                    $(this).find('.defaultAddress').prop('checked',false);
                                  }
                                })
                                  //$('.orderList li:first').find('.defaultAddress').prop('checked',true);
                                 // $('.orderList li:first').addClass('check');
                                }
                                $('.changeYes').attr({'data-amount':$amountInput.val(),'data-id':yesChangeId,'data-addressId':addressId});
                                $addressId = $('.changeYes').attr('data-addressId');
                        }
                      });
                    }
                  });
              }
              else
              {
                 $.layer({
                    type: 1,
                    closeBtn: [0,true],
                    title: "&nbsp;",
                    area: ['450px', '190px'],
                    border: [1, 1, '#cecfd0'],
                    page: {
                        html: '<div class="tipsWrap w450"><div class="tipsTxt"><i class="iconfont tipIco">&#xe63c;</i><span>您还未设置收货地址，是否去账户中心进行设置？</span></div><div class="tipsBtnBar"><a href="/member/score/receivingInfo.html" class="okBtn">现在就去</a><a href="javascript:;" class="cancleBtn">下次吧</a></div></div>'
                    }
               });
               $('.cancleBtn').click(function(){
                  layer.closeAll();
               })
              }
          }
          else if(parseInt($remainAmount) <= 0)
          {
             $.layer({
                  type: 1,
                  closeBtn: [0,true],
                             title: "&nbsp;",
                  area: ['384px', '186px'],
                  border: [1, 1, '#cecfd0'],
                  time:3,
                  page: {
                      html: '<div class="tipsWrap w384"><div class="tipsTxt"><i class="iconfont okIco">&#xe63d;</i><span>没有库存了哦，下次再来吧！</span></div><div class="tipsMsg"><i class="tipsTime">3</i>秒后窗口自动关闭</div></div>'
                  },
                  success:function(){
                   var time = 3;
                   function tipsTime(){
                    time--;
                    $(".tipsTime").html(time)
                    if(time == 0)
                    {
                     clearInterval(timeCount)
                    }
                   }
                   var timeCount = setInterval(function(){tipsTime()},1000);
                  }
             });
          }
      });
    })
  }
  else if($validScore < $calculate)
  {
    $('.yesChange').html('积分不足');
  }
  

  //点击事件选择默认地址
  $('.orderList li').live('click',function(){
    $(this).addClass('check').siblings().removeClass('check');
    $(this).find('input').prop('checked',true);
    $addressId = $(this).attr('data-addressId');
  })

  //确认订单
  $('.changeYes').live('click',function(){
    $.ajax({
          url:"/member/score/convert/doConvert.html?randomTime=" + (new Date()).getTime(),
          type:"get",
          dataType:"json",
          cache:false,
          data:{goodsId:$(this).attr("data-id"),convertNum:$(this).attr("data-amount"),addressId:$addressId,remark:$("#remark").val()},
          success:function(json){
              layer.closeAll();
              if(json.result == true)
              {
                $.layer({
                  type: 1,
                  closeBtn: [0,true],
                  title: "&nbsp;",
                  area: ['384px', '186px'],
                  border: [1, 1, '#cecfd0'],
                  time:3,
                  page: {
                      html: '<div class="tipsWrap w384"><div class="tipsTxt"><i class="iconfont okIco">&#xe63d;</i><span>兑换成功！</span></div><div class="tipsMsg"><i class="tipsTime">3</i>秒后窗口自动关闭</div></div>'
                  },
                  close: function(index){
                        window.location.reload();
                  },
                  end: function(){
                        window.location.reload();
                  },
                  success:function(){
                   var time = 3;
                   function tipsTime(){
                    time--;
                    $(".tipsTime").html(time)
                    if(time == 0)
                    {
                     clearInterval(timeCount)
                    }
                   }
                   var timeCount = setInterval(function(){tipsTime()},1000);
                  }
                });
              }
              else
              {
                $.layer({
                  type: 1,
                  closeBtn: [0,true],
                  title: "&nbsp;",
                  area: ['384px', '186px'],
                  border: [1, 1, '#cecfd0'],
                  time:3,
                  page: {
                      html: '<div class="tipsWrap w384"><div class="tipsTxt"><i class="iconfont okIco">&#xe63d;</i><span>'+json.msg+'</span></div><div class="tipsMsg"><i class="tipsTime">3</i>秒后窗口自动关闭</div></div>'
                  },
                  close: function(index){
                        window.location.reload();
                  },
                  end: function(){
                        window.location.reload();
                  },
                  success:function(){
                   var time = 3;
                   function tipsTime(){
                    time--;
                    $(".tipsTime").html(time)
                    if(time == 0)
                    {
                     clearInterval(timeCount)
                    }
                   }
                   var timeCount = setInterval(function(){tipsTime()},1000);
                  }
                });
              }
          }
        })
  });
});